package cn.beforedark.yygh.cmn.controller;

import cn.beforedark.yygh.cmn.service.DictService;
import cn.beforedark.yygh.common.result.R;
import cn.beforedark.yygh.model.cmn.Dict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * /admin/cmn/dict
 */
@RestController
@RequestMapping("/admin/cmn/dict")
// @CrossOrigin
public class DictController {

    @Autowired
    private DictService dictService;


    /**
     * 根据 pid 查询所有子字典
     *
     * @param pid 父 id
     * @return vo
     */
    @GetMapping("/childList/{pid}")
    public R getChildListByPid(@PathVariable Long pid) {
        List<Dict> list = dictService.getChildListByPid(pid);
        return R.ok().data("items", list);
    }


    /**
     * 根据 dictCode 查询所有子字典
     *
     * @param dictCode 字典编码 dictCode
     * @return vo
     */
    @GetMapping("/getChildListByDictCode/{dictCode}")
    public R getChildListByDictCode(@PathVariable("dictCode") String dictCode) {

        Dict dict = dictService.getByDictCode(dictCode);

        List<Dict> list = dictService.getChildListByPid(dict.getId());

        return R.ok().data("items", list);
    }


    /**
     * 导出数据字典 Excel
     *
     * @param response Excel文件
     */
    @GetMapping("/exportExcel")
    public void download(HttpServletResponse response) {
        //  http://localhost:8202/admin/cmn/dict/exportExcel
        dictService.exportExcel(response);
    }


    /**
     * 导入 Excel 用以实现 修改/新增 字典功能
     *
     * @param file Excel 文件
     * @return vo
     */
    @PostMapping("/importExcel")
    public R upload(MultipartFile file) {
        dictService.importExcel(file);
        return R.ok();
    }

    /**
     * 根据 value 查询字典名称
     */
    @GetMapping("/getNameByValue/{value}")
    public String getNameByValue(@PathVariable("value") Long value) {
        return dictService.getNameByDictCodeAndValue("", value);
    }

    /**
     * 根据 dictCode 和 value 查询字典名称
     */
    @GetMapping("/getNameByDictCode/{dictCode}/{value}")
    public String getNameByDictCode(@PathVariable("dictCode") String dictCode,
                                    @PathVariable("value") Long value) {
        return dictService.getNameByDictCodeAndValue(dictCode, value);
    }


}
























